import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:openchina/common/event_bus.dart';
import 'package:openchina/constants/constants.dart';
import 'package:openchina/models/tweet_new.dart';
import 'package:openchina/pages/login_web_page.dart';
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';
import 'package:openchina/widgets/tweet_new_item.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class TweetPage extends StatefulWidget {
  @override
  _TweetPageState createState() => _TweetPageState();
}

class _TweetPageState extends State<TweetPage>
    with SingleTickerProviderStateMixin {
  List _tabTitles = ['最新', '热门'];

//  List latesTweetList;
//  List hotTweenList;
  int curPage = 1;
  TabController _controller = null;
  bool isLogin;
  int pageSize = 10;
  List<TweetNew> allTweetNews = [];
  List<TweetNew> hotTweetNews = [];
  int user = 0;
  bool isRefresh = false;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onLoading() async {
    _get_tweet_list(user);
    _refreshController.loadComplete();
  }

  void _onRefresh() async {
    isRefresh = true;
    curPage = 1;
    setState(() {
      allTweetNews.clear();
    });
    _get_tweet_list(user);
    _refreshController.refreshCompleted();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TabController(length: _tabTitles.length, vsync: this);
    _controller.addListener((){
      switch (_controller.index) {
        case 0:
          curPage=1;
          user = 0;
          _get_tweet_list(user);
          break;
        case 1:
          curPage=1;
          user = 1;
          _get_tweet_list(user);
          break;
      }
    });
    _get_tweet_list(0);
    eventBus.on<LoginEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = true;
      });
      _get_tweet_list(user);
    });
    eventBus.on<LogoutEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = false;
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }

  void _get_tweet_list(int curUser) {
    DataUtil.isLogin().then((isLogin) {
      if (!mounted) return;
      if (isLogin != null) {
        setState(() {
          this.isLogin = isLogin;
        });
        DataUtil.getTokenAccess().then((accessToken) {
          if (!mounted) return;
          if (accessToken != null) {
            Map<String, dynamic> params = new Map<String, dynamic>();
            params['access_token'] = accessToken;
            params['user'] = curUser;
            params['pageSize'] = pageSize;
            params['page'] = curPage;
            params['dataType'] = AppInfo.JSON;
            NetUtil.get(AppUrls.TWEET_LIST, params).then((data) {
              Map<String, dynamic> map = json.decode(data);
              switch (curUser) {
                case 0:
                  print('动弹最新 $data');
                  List tweetlist = map['tweetlist'];
                  List<TweetNew> curPageTweetNews = [];
                  for (int i = 0; i < tweetlist.length; i++) {
                    TweetNew tweetNew = new TweetNew();
                    tweetNew.author = tweetlist[i]['author'];
                    tweetNew.id = tweetlist[i]['id'];
                    tweetNew.portrait = tweetlist[i]['portrait'];
                    tweetNew.authorid = tweetlist[i]['authorid'];
                    tweetNew.body = tweetlist[i]['body'];
                    tweetNew.pubDate = tweetlist[i]['pubDate'];
                    tweetNew.commentCount = tweetlist[i]['commentCount'];
                    tweetNew.imgBig = tweetlist[i]['imgBig'];
                    curPageTweetNews.add(tweetNew);
                  }
                  if(curPageTweetNews.length==10){
                    curPage++;
                  }
                  if (!mounted) return;
                  setState(() {
                    allTweetNews.addAll(curPageTweetNews);
                  });
                  break;
                case 1:
                  print('动弹热门 $data');
                  List tweetlist = map['tweetlist'];
                  List<TweetNew> curPageTweetNews = [];
                  for (int i = 0; i < tweetlist.length; i++) {
                    TweetNew tweetNew = new TweetNew();
                    tweetNew.author = tweetlist[i]['author'];
                    tweetNew.id = tweetlist[i]['id'];
                    tweetNew.portrait = tweetlist[i]['portrait'];
                    tweetNew.authorid = tweetlist[i]['authorid'];
                    tweetNew.body = tweetlist[i]['body'];
                    tweetNew.pubDate = tweetlist[i]['pubDate'];
                    tweetNew.commentCount = tweetlist[i]['commentCount'];
                    tweetNew.imgBig = tweetlist[i]['imgBig'];
                    curPageTweetNews.add(tweetNew);
                  }
                  if (!mounted) return;
                  setState(() {
                    hotTweetNews.addAll(curPageTweetNews);
                  });
                  break;
              }
            });
          }
        });
      }
    });
  }

  Future _login(BuildContext context) async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => LoginWebPage(),
      ),
    );
    if (result != null && result == 'refresh') {
      //跳转过去后下一个界面约定子弹表示登录成功
      eventBus.fire(LoginEvent()); //登录成功通知loginEvent
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          child: TabBar(
              labelColor: Color(0x67055700),
              unselectedLabelColor: Color(0x77777777),
              controller: _controller,
              tabs: _tabTitles
                  .map((title) => Tab(
                        text: title,
                      ))
                  .toList()),
        ),
        Expanded(
          child: TabBarView(
              physics: NeverScrollableScrollPhysics(),
              controller: _controller,
              children: [
                _buildSmartRefresher(),
                _buildSmartHot(),
              ]),
        ),
      ],
    );
  }

  Widget _buildSmartHot() {
    if (isLogin == null || !isLogin) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('部分限制需登录才能查看'),
            InkWell(
              onTap: () async {
                await _login(context);
              },
              child: Text('登录'),
            )
          ],
        ),
      );
    }
    if (hotTweetNews == null || hotTweetNews.length == 0) {
//      _get_tweet_list(user);
      return new Center(
        child: CupertinoActivityIndicator(),
      );
    }
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text(
              "加载更多",
              style: TextStyle(color: Color(0x89657423)),
            );
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("Load Failed!Click retry!");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("release to load more");
          } else {
            body = Text("没有更多数据了");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: ListView.builder(
        itemBuilder: (context, index) => Card(
          child: Center(
            child: TweetNewItem(
              tweetNew: hotTweetNews[index],
            ),
          ),
        ),
        itemExtent: 150.0,
        itemCount: hotTweetNews.length,
      ),
    );
  }

  Widget _buildSmartRefresher() {
    if (isLogin == null || !isLogin) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('部分限制需登录才能查看'),
            InkWell(
              onTap: () async {
                await _login(context);
              },
              child: Text('登录'),
            )
          ],
        ),
      );
    }
    if (allTweetNews == null || allTweetNews.length == 0) {
      return new Center(
        child: Text('数据加载中...'),
      );
    }
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropMaterialHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text(
              "加载更多",
              style: TextStyle(color: Color(0x89657423)),
            );
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("Load Failed!Click retry!");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("release to load more");
          } else {
            body = Text("没有更多数据了");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: ListView.builder(
        itemBuilder: (context, index) => Card(
          child: Center(
            child: TweetNewItem(
              tweetNew: allTweetNews[index],
            ),
          ),
        ),
        itemExtent: 150.0,
        itemCount: allTweetNews.length,
      ),
    );
  }
}
